package com.googlecode.horncomb.web.util;

import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.View;

public class ModelAndViewUtil {
	private static Log logger = LogFactory.getLog(ModelAndViewUtil.class);

	@SuppressWarnings("unchecked")
	public static ModelAndView createModelAndView(Object view, Map controlModel) {
		Assert.notNull(view);
		ModelAndView mav = null;
		if (ClassUtils.isAssignableValue(View.class, view)) {
			mav = new ModelAndView();
			mav.setView((View) view);
		} else {
			if (!(view instanceof String)) {
				logger
						.warn("view is not the instance of String or View, force to convert to String (call toString())");
			}
			mav = new ModelAndView(view.toString());
		}
		if (mav != null && controlModel != null) {
			mav.addAllObjects(controlModel);
		}
		return mav;
	}
}
